Sort a vector or a list, given one or more auxiliary functions.

sort_by(x, ..., method = c("auto", "shell", "radix"))

Arguments

x

vector or list to sort.

...

one or several functions to apply to x. Use descending for reversed order.

method

the method for ties (see order).

Value

A vector or list containing rearranged elements of x.

Details

The output of the first function will be used as first key for sorting, the output of the second function as second key, and so on... Therefore, these outputs should be sortable (i.e. atomic vectors).

sort_by is inspired by sortBy in Haskell.

See also

order which is used for rearranging elements.

Examples

sort_by(-3:2, abs)
#> [1] 0 -1 1 -2 2 -3
sort_by(-3:2, abs, function(x) -x)
#> [1] 0 1 -1 2 -2 -3
sort_by(list(5:7, 0, 1:4), length)
#> [[1]] #> [1] 0 #> #> [[2]] #> [1] 5 6 7 #> #> [[3]] #> [1] 1 2 3 4 #>
sort_by(list(1:2, 3:4, 5), length, descending(sum))
#> [[1]] #> [1] 5 #> #> [[2]] #> [1] 3 4 #> #> [[3]] #> [1] 1 2 #>